package com.xuebang.admin.web.displaytag;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.displaytag.pagination.PaginatedList;
import org.displaytag.properties.SortOrderEnum;

import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.xuebang.admin.dao.Pagination;

public class DisplayPaginatedList<T> implements PaginatedList {

	private Pagination<T> pagination;
	private String sortCriterion;
	private SortOrderEnum sortDirection;
	private int index;

	public DisplayPaginatedList(HttpServletRequest request) {
		this.sortCriterion = request.getParameter("sort");
		String dir = request.getParameter("dir");
		if (dir == null) {
			dir = "asc";
		}
		this.sortDirection = "desc".equals(dir) ? SortOrderEnum.DESCENDING
				: SortOrderEnum.ASCENDING;
		String page = request.getParameter("page");
		// objectsPerPage = DEFAULT_PAGE_SIZE;
		index = page == null ? 0 : Integer.parseInt(page) - 1;
	}

	public SortOrderEnum getSortDirection() {
		ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder
				.getRequestAttributes();
		HttpServletRequest req = attrs.getRequest();
		try {
			String sortDirection = ServletRequestUtils.getStringParameter(req,
					"dir");
			if (sortDirection == null || sortDirection.equals("asc")) {
				return SortOrderEnum.ASCENDING;
			} else {
				return SortOrderEnum.DESCENDING;
			}
		} catch (ServletRequestBindingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return SortOrderEnum.ASCENDING;
		}
	}

	public void setSortDirection(SortOrderEnum sortDirection) {
		this.sortDirection = sortDirection;
	}

	public DisplayPaginatedList(Pagination<T> pagination) {
		this.pagination = pagination;
	}

	public List<T> getList() {
		return pagination.getData();
	}

	
	public int getPageNumber() {
		return pagination.page;
	}

	
	public int getObjectsPerPage() {
		return pagination.perPage;
	}

	
	public int getFullListSize() {
		return pagination.total;
	}

	
	public String getSortCriterion() {
		if (this.sortCriterion != null) {
			return this.sortCriterion;
		} else {
			ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder
					.getRequestAttributes();
			HttpServletRequest req = attrs.getRequest();
			try {
				return ServletRequestUtils.getStringParameter(req, "sort");
			} catch (ServletRequestBindingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return null;
			}
		}

	}

	
	public String getSearchId() {
		return null;
	}

	public void setSortCriterion(String sortCriterion) {
		this.sortCriterion = sortCriterion;
	}

	public int getIndex() {
		return index;
	}

	public void setIndex(int index) {
		this.index = index;
	}

}
